package com.lw.common.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Environment.DIRECTORY_DOCUMENTS
import android.os.StrictMode
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import java.io.*
import java.util.*

/**
 * 文件读取工具类
 */
object FileUtil {
    /**
     * 读取文件内容，作为字符串返回
     */
    @Throws(IOException::class)
    fun readFileAsString(filePath: String): String {
        val file = File(filePath)
        if (!file.exists()) {
            throw FileNotFoundException(filePath)
        }
        if (file.length() > 1024 * 1024 * 1024) {
            throw IOException("File is too large")
        }
        val sb = StringBuilder(file.length().toInt())
        // 创建字节输入流  
        val fis = FileInputStream(filePath)
        // 创建一个长度为10240的Buffer
        val buf = ByteArray(10240)
        // 用于保存实际读取的字节数  
        var hasRead: Int
        while (fis.read(buf).also { hasRead = it } > 0) {
            sb.append(String(buf, 0, hasRead))
        }
        fis.close()
        return sb.toString()
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    @Throws(IOException::class)
    fun readFileByBytes(filePath: String): ByteArray {
        val file = File(filePath)
        return if (!file.exists()) {
            throw FileNotFoundException(filePath)
        } else {
            val bos = ByteArrayOutputStream(file.length().toInt())
            var `in`: BufferedInputStream? = null
            try {
                `in` = BufferedInputStream(FileInputStream(file))
                val bufSize: Short = 1024
                val buffer = ByteArray(bufSize.toInt())
                var len1: Int
                while (-1 != `in`.read(buffer, 0, bufSize.toInt()).also { len1 = it }) {
                    bos.write(buffer, 0, len1)
                }
                bos.toByteArray()
            } finally {
                try {
                    `in`?.close()
                } catch (var14: IOException) {
                    var14.printStackTrace()
                }
                bos.close()
            }
        }
    }

    /**
     * 保存文件到SD卡
     */
    fun saveFile(fileName: String, data: ByteArray, context: Context) {
//        val dir = File(Environment.getExternalStorageDirectory(), "files")
//        if (!dir.exists()) {
//            dir.mkdirs()
//        }
        val file = File(context.getExternalFilesDir(DIRECTORY_DOCUMENTS), fileName)
        var outStream: FileOutputStream? = null
        outStream = try {
            FileOutputStream(file)
        } catch (e: FileNotFoundException) {
            throw RuntimeException(e)
        }
        outStream?.write(data)
        outStream?.close()
    }

    /**
     * 根据文件路径,使用第三方APP打开
     */
    fun openFile(fileName: String, context: Context) {
        try {
            val path = context.getExternalFilesDir(DIRECTORY_DOCUMENTS)?.path + "/$fileName"
            Log.d("sdfsfd", path)
            val intent = Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            val uri: Uri;
            // 7.0及以上，需要用到provider
            val file = File(path)
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION//FLAG_GRANT_WRITE_URI_PERMISSION
            uri = FileProvider.getUriForFile(context, "com.example.base_kotlin.file-provider", file)
            intent.setDataAndType(uri, getMIMEType(file))
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "文件打开失败", Toast.LENGTH_LONG).show()
        }
    }

    /**
     * 判断文件MimeType的method
     */
    private fun getMIMEType(f: File): String {
        var type: String = ""
        var fName: String = f.name
        /* 取得扩展名 */
        var end: String = fName.substring(fName.lastIndexOf(".") + 1, fName.length)
            .lowercase(Locale.getDefault());

        /* 按扩展名的类型决定MimeType */
        if (end == "m4a" || end == "mp3" || end == "mid" || end == "xmf" || end == "ogg" || end == "wav" || end == "mpga") {
            return "audio/*";
        } else if (end == "3gp" || end == "mp4" || end == "mpg4" || end == "mov") {
            return "video/*";
        } else if (end == "jpg" || end == "gif" || end == "png" || end == "jpeg" || end == "bmp") {
            return "image/*";
        } else if (end == "txt" || end == "log" || end == "xml") {
            return "text/plain"
        } else if (end == "pdf") {
            return "application/pdf"
        } else if (end == "doc") {
            return "application/msword"
        } else if (end == "docx") {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        } else if (end == "xls") {
            return "application/vnd.ms-excel"
        } else if (end == "xlsx") {
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        } else if (end == "exe") {
            return "application/octet-stream"
        } else if (end == "ppt") {
            return "application/vnd.ms-powerpoint"
        } else if (end == "pptx") {
            return "application/vnd.openxmlformats-officedocument.presentationml.presentation"
        } else if (end == "tar") {
            return "application/x-tar"
        } else if (end == "tgz") {
            return "application/x-compressed"
        } else if (end == "zip") {
            return "application/x-zip-compressed"
        } else if (end == "apk") {
            /* android.permission.INSTALL_PACKAGES */
            //用下载并自动安装apk包
            return "application/vnd.android.package-archive"
        } else {
            /* 如果无法直接打开，就弹出软件列表给用户选择 */
            return "*/*"
        }
    }
}